'use strict';

let { user, createQuestionair, questionair } = require('../model');
const auth = require('../tools/auth');
let db = require('../db');



//显示首页
let index_fn = async (ctx, next) => {

    ctx.render('index.html');
};
// 显示用户登录界面
let login_user = async (ctx, next) => {

    ctx.render('user.html');
};

//显示管理员登录界面

let login_admin = async (ctx, next) => {
    ctx.render('admin.html');
};
// 显示注册界面
let register_fn = async (ctx, next) => {
    ctx.render('register.html');
};

//显示修改密码页面
let vim_fn = async (ctx, next) => {
    ctx.render("vimPwd.html");
}
// 处理登录请求
//已经在数据库里添加了超级管理员
//用户名为：admin ; 密码：123
let loginDone_fn = async (ctx, next) => {
    // 获取从前端传来的数据（用户信息）
    let uid = ctx.request.body.username.trim() || '';
    let pwd = ctx.request.body.password.trim() || '';

    let res = '';

    if (uid.length > 0 && pwd.length > 0) {
        let row = await user.findOne({
            where: {
                username: uid,
                password: pwd
            }
        });
        let u2Json = JSON.parse(JSON.stringify(row));
   
        if (u2Json !== null) {
            if (u2Json.isAdmin === '1') {
                ctx.session.userId = u2Json.id;
                ctx.session.userName = u2Json.username;
                ctx.render('user.html');
                res = { code: 200, msg: '登录成功' };
                ctx.body = JSON.stringify(res);
            } else if (u2Json.isAdmin === '2'){
                ctx.session.userId = row.id;
                ctx.session.userName = row.username;
                ctx.render('manager.html'); 
                
                res = { code: 200, msg: '登录成功' };
                ctx.body = JSON.stringify(res);
            }
        } else {
            res = { code: 1000, msg: '用户名或密码错误，请确认后重试' };
            ctx.body = JSON.stringify(res);
        }

    } else {
        res = { code: 1000, msg: '用户名和密码不能为空' };
        ctx.body = JSON.stringify(res);
    }
    // ctx.body = JSON.stringify(res);
};




// 处理注册请求
let registerDone_fn = async (ctx, next) => {
    // 获取从前端传来的数据（用户信息）
    let uid = ctx.request.body.username || '';
    let pwd = ctx.request.body.password || '';
    let confirmpwd = ctx.request.body.tryPwd || '';
    let res = '';
    console.log(uid);
    console.log(pwd);
    console.log(confirmpwd);
    // 判断用户名、密码是否为空，为空则返回提示信息；不为空则尝试从数据库中查询是否有同名用户，如果没有，则创建用户；如果有，则返回提示信息；
    // 初步尝试then的玩法，出现了一些顺序问题（前端获取的返回数据为空的情况）
    if (uid.length > 0 && pwd.length > 0 && pwd === confirmpwd) {
        let row = await user.findOne({
            where: {
                username: uid
            }
        });
        let u2Json = JSON.stringify(row);
        if (u2Json === 'null') {
            let u1 = await user.create({
                username: uid,
                password: pwd
            });
            let u1Json = JSON.stringify(u1);
            if (u1Json !== 'null') {
                res = { code: 200, msg: '用户注册成功,请选择管理员登录或普通用户登录' };
            } else {
                res = { code: 1000, msg: '因为服务器或者网络原因，用户未注册成功' };
            }
        } else {
            res = { code: 1000, msg: '当前用户名已经注册，请确认后重试' };
        }
    } else {
        res = { code: 1000, msg: '用户名和密码不能为空，且两密码应该一致' };
    }
    // 返回消息
    ctx.body = JSON.stringify(res);
};
// 注销
let logout_fn = async (ctx, next) => {
    ctx.session = null;
    ctx.body = { code: 200, msg: '注销成功' };
}
// 创建调查问卷的方法
let create_fn = async (ctx, next) => {

    //调查问卷发起人
    let promoterId = ctx.session.userId;
    // console.log(ctx.request.body.topic);
    //问卷主题
    let topic = ctx.request.body.topic || '';
    // console.log(ctx.request.body.introduction);
    //问卷说明
    let introduction = ctx.request.body.introduction.trim() || '';

    //问卷问题
    let question1 = ctx.request.body.questionOne || '';
    let question2 = ctx.request.body.questionTwo || '';
    let question3 = ctx.request.body.questionThree || '';
    let question4 = ctx.request.body.questionFour || '';
    let question5 = ctx.request.body.questionFive || '';
    let question6 = ctx.request.body.questionSix || '';
    let question7 = ctx.request.body.questionSeven || '';
    let question8 = ctx.request.body.questionEight || '';
    let question9 = ctx.request.body.questionNine || '';
    let question10 = ctx.request.body.questionTen || '';
    // console.log(promoterId);
    // console.log(topic);
    // console.log(introduction);
    // console.log(question1);

    // 添加调查问卷
    let addQuestionair = await createQuestionair.create({
        promoterId: promoterId,
        topic: topic,
        introduction: introduction,
        questionOne: question1,
        questionTwo: question2,
        questionThree: question3,
        questionFour: question4,
        questionFive: question5,
        questionSix: question6,
        questionSeven: question7,
        questionEight: question8,
        questionNine: question9,
        questionTen: question10,
    });

    let data = JSON.parse(JSON.stringify(addQuestionair));
    data.createdtime = getTime(JSON.parse(addQuestionair.createdAt));
    // console.log(data.createdtime);
    ctx.body = { code: 200, data, msg: '创建调差问卷成功' };
}

//管理员后台系统

let manager_fn = async (ctx, body) => {
    // 用户名
    var username = ctx.session.userName;

    // 管理员首页最新问卷信息
    var NewQS = JSON.parse(JSON.stringify(await createQuestionair.findAll({
        order: [
            ['createdAt', 'desc']
        ],
        where: {
            state: '1'
        }
    })));
    // console.log(NewQS);

    // 所有用户
    var allUser = JSON.parse(JSON.stringify(await user.findAll()));

    NewQS.forEach(QS => {
        // console.log(QS);
        // 问卷创建时间
        QS.createdTime = getTime(JSON.parse(QS.createdAt));

        // 发布人
        QS.publishUserName = allUser.filter(row => {
            return QS.promoterId === row.id;
        })[0].username;
        // console.log(QS.publishUserName);
    })


    var obj = {
        NewQS,
        allUser,
        username
    }
    ctx.render('manager.html', obj);
}

//问卷调查结果
let result_fn = async (ctx, body) => {
    var QSId = ctx.query.id;
    //获取调查问卷的所有数据
    var questions = JSON.parse(JSON.stringify(await createQuestionair.findAll()));


    //答案表
    var scores = JSON.parse(JSON.stringify(await questionair.findAll({
        where: {
            questionairId: QSId
        }
    })));

    //把答案表里面的问卷id与创建调查问卷的id相关联

    // scores.forEach(QS=>{
    //     QS.questionairId=questions.filter(item=>{
    //         return item.Id===QS.questionairId 
    //     })
    // })
    // 查找问卷主题
    scores.forEach(QSA => {
        QSA.topic = questions.filter(qsa => {
            return QSA.questionairId === qsa.id
        })[0].topic;
        // console.log(QSA.topic);
    })

    // 查找问卷简介
    scores.forEach(QSA => {
        QSA.introduction = questions.filter(qsa => {
            return QSA.questionairId === qsa.id
        })[0].introduction;
        console.log(QSA.introduction);

        QSA.sumScore = parseInt(QSA.oneAnswer) + parseInt(QSA.twoAnswer) + parseInt(QSA.threeAnswer) + parseInt(QSA.fourAnswer) + parseInt(QSA.fiveAnswer) + parseInt(QSA.sixAnswer) + parseInt(QSA.sevenAnswer) + parseInt(QSA.eightAnswer) + parseInt(QSA.nineAnswer) + parseInt(QSA.tenAnswer)
        QSA.avgScore = (parseInt(QSA.oneAnswer) + parseInt(QSA.twoAnswer) + parseInt(QSA.threeAnswer) + parseInt(QSA.fourAnswer) + parseInt(QSA.fiveAnswer) + parseInt(QSA.sixAnswer) + parseInt(QSA.sevenAnswer) + parseInt(QSA.eightAnswer) + parseInt(QSA.nineAnswer) + parseInt(QSA.tenAnswer)) / 10
    })
    var obj = {
        questions,
        scores
    }
    ctx.render('result.html', obj);

}
//删除调查问卷

let delete_fn = async (ctx, body) => {
    var qsId = ctx.request.body.QSid.trim();
    console.log(qsId);
    //  获取点击问卷的id传入前端
    await createQuestionair.update(
        {
            state: '2'
        }, {
        where: {
            id: qsId
        }

    })
    let res = "";
    res = { code: 200, msg: "删除成功" };
    ctx.body = JSON.stringify(res);
}


//所有问卷(已发布的调查问卷)
let all_fn = async (ctx, body) => {
    var promoterId = ctx.session.userId;
    var username = ctx.session.userName;
    var topic = ctx.session.topic;

    var findUser = JSON.parse(JSON.stringify(await user.findAll({
        where: {
            id: promoterId,
            username: username
        }


    })))

    var currentUserQ = JSON.parse(JSON.stringify(await createQuestionair.findAll({
        where: {
            promoterId: promoterId,
            state: '1',

        }

    })
    ));
    currentUserQ.forEach(element => {
        element.createdTime = getTime(JSON.parse(element.createdAt));
        // console.log(element.createdAt);


    });
    findUser.forEach(element => {
        element.username = username;
        // console.log(element.username);
    });


    var obj = {
        findUser,
        currentUserQ,
        topic

    }



    ctx.render('all.html', obj);

}

//参与调查页面
let questionair_fn = async (ctx, next) => {

    let promoterId = ctx.session.userId || '';
    let questionairId = ctx.request.body.QSId;
    let answer1 = ctx.request.body.oneAnswer || '';
    let answer2 = ctx.request.body.twoAnswer || '';
    let answer3 = ctx.request.body.threeAnswer || '';
    let answer4 = ctx.request.body.fourAnswer || '';
    let answer5 = ctx.request.body.fiveAnswer || '';
    let answer6 = ctx.request.body.sixAnswer || '';
    let answer7 = ctx.request.body.sevenAnswer || '';
    let answer8 = ctx.request.body.eightAnswer || '';
    let answer9 = ctx.request.body.nineAnswer || '';
    let answer10 = ctx.request.body.tenAnswer || '';



    //选项得分存入答案表


    let options = await questionair.create({
        promoterId: promoterId,
        questionairId: questionairId,
        oneAnswer: answer1,
        twoAnswer: answer2,
        threeAnswer: answer3,
        fourAnswer: answer4,
        fiveAnswer: answer5,
        sixAnswer: answer6,
        sevenAnswer: answer7,
        eightAnswer: answer8,
        nineAnswer: answer9,
        tenAnswer: answer10,
    });
    // console.log(questionairId);
    // console.log(promoterId);
    // 


    let data = JSON.parse(JSON.stringify(options));
    ctx.body = { code: 200, data, msg: '填写完成' };


}

//找到填写调查问卷页面
let findPage = async (ctx, next) => {
    var QSId = ctx.query.id;
    // console.log(QSId);
    var findSomething = JSON.parse(JSON.stringify(await createQuestionair.findOne({
        where: {
            id: QSId
        }
    })))

    var topic = findSomething.topic;
    var questionOne = findSomething.questionOne;
    var questionTwo = findSomething.questionTwo;
    var questionThree = findSomething.questionThree;
    var questionFour = findSomething.questionFour;
    var questionFive = findSomething.questionFive;
    var questionSix = findSomething.questionSix;
    var questionSeven = findSomething.questionSeven;
    var questionEight = findSomething.questionEight;
    var questionNine = findSomething.questionNine;
    var questionTen = findSomething.questionTen;
    //   console.log(findSomething.id);
    // console.log(topic);
    var obj = {
        QSId,
        findSomething,
        topic,
        questionOne,
        questionTwo,
        questionThree,
        questionFour,
        questionFive,
        questionSix,
        questionSeven,
        questionEight,
        questionNine,
        questionTen
    }
    ctx.render('qustionair.html', obj);
}


let questionairDome_fn = async (ctx, next) => {
    //获取用户点击前往的问卷id
    var qsId = ctx.request.body.QSid.trim();

    // console.log(qsId);
    //  获取点击问卷的id传入前端
    var url = '/findPage/?id=' + qsId; //SQ1/?id=qsId
    // console.log(url);

    let res = "";
    res = { code: 200, url: url };
    ctx.body = JSON.stringify(res);


}

//修改密码
let makeSure = async (ctx, next) => {
    var QSId = ctx.session.userId;
    let res = '';
    console.log(QSId);
    var password = ctx.request.body.pwd|| '';
    var tryPassword = ctx.request.body.tryPwd || '';
    console.log(password);
    console.log(tryPassword);

    if (password.length > 0 && tryPassword.length > 0 && password === tryPassword) {
        var findUser = await user.findOne({
            where: {
                id: QSId
            }
        })
        let row = JSON.stringify(findUser);
        if (row.length > 0 && password===tryPassword) {
            var vim = await user.update({
                password: tryPassword
            }, {
                where: {
                    id: QSId
                }
            })
            let json1 = JSON.stringify(vim);
            console.log(json1);
            if (json1 !== 'null') {
                res = { code: 200, msg: '修改密码成功' };
             
                
            } else {
                res = { code: 1000, msg: '修改密码失败' };
                
            }

        } else {
            res = { code: 1000, msg: '当前用户不存在' };

        }
      
    } else {
        res = { code: 1000, msg: '不能为空,输入的两次密码必须一致' };
    }
    console.log(res);
  
     ctx.body = JSON.stringify(res);
}


//显示时间
function getTime(time) {
    let date = new Date(time);
    let y = date.getFullYear();
    let m = date.getMonth() + 1;
    let d = date.getDate();
    let h = date.getHours();
    let mi = date.getMinutes();
    if (m < 10) {
        m = "0" + m;
    }
    if (d < 10) {
        d = "0" + d;
    }
    return (y + '-' + m + '-' + d + ' ' + h + ':' + mi);
}


module.exports = {
    '/': ['get', auth, index_fn],
    '/admin': ['get', auth, login_admin],
    '/user': ['get', auth, login_user],
    '/logout': ['post', auth, logout_fn],
    '/register': ['get', register_fn],
    '/loginDone': ['post', loginDone_fn],
    '/registerDone': ['post', registerDone_fn],
    '/create': ['post', create_fn],
    '/all': ['get', all_fn],
    '/manager': ['get', auth, manager_fn],
    '/qustionair': ["post", questionair_fn],
    '/questionairDome': ["post", questionairDome_fn],
    '/findPage': ['get', findPage],
    '/result': ['get', result_fn],
    '/delete': ['post', delete_fn],
    '/vimPwd': ["post", makeSure],
    '/vim': ['get', vim_fn]


}

